<template>
  <div class="dataset-component">
    <!-- 左侧数据集列表 -->
    <div class="dataset-sidebar">
      <div class="sidebar-header">
        <h2>数据集列表</h2>
      </div>

      <div class="sidebar-content">
        <div v-if="loading" class="loading-state">
          <el-skeleton :rows="5" animated />
        </div>
        <div v-else-if="datasets.length > 0" class="dataset-list">
          <div
            v-for="dataset in datasets"
            :key="dataset.id"
            class="dataset-item"
            :class="{ active: currentDataset?.id === dataset.id }"
            @click="selectDataset(dataset)"
          >
            <div class="dataset-info">
              <div class="dataset-title">
                <span class="dataset-type" :class="{ shared: dataset.is_shared }">
                  {{ dataset.is_shared ? '共享' : '本地' }}
                </span>
                {{ dataset.name }}
              </div>
            </div>
            <div class="dataset-actions" v-if="!dataset.is_shared">
              <el-icon class="delete-icon" @click.stop="confirmDeleteDataset(dataset)"
                ><Delete
              /></el-icon>
            </div>
          </div>
        </div>
        <div v-else class="empty-state">
          <div class="empty-icon">
            <el-icon><i-ep-files /></el-icon>
          </div>
          <div class="empty-text">暂无数据集</div>
        </div>
      </div>
    </div>

    <!-- 右侧数据集详情 -->
    <div class="dataset-detail">
      <DatasetDetail
        v-if="currentDataset"
        :current-dataset="currentDataset"
        :is-dark-mode="isDarkMode"
      />
      <div v-else class="empty-detail">
        <el-empty description="请选择一个数据集" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import DatasetDetail from '../../client/components/layout/DatasetDetail.vue'
import { getMyDatasets } from '../../client/api/dataset'
import { deleteMyDataset } from '../../client/api/analysis'
import { useRoute } from 'vue-router'

const route = useRoute()

defineProps({
  isDarkMode: {
    type: Boolean,
    default: false,
  },
})

// 数据集列表
const datasets = ref([])
const currentDataset = ref(null)
const loading = ref(false)

// 根据ID选择数据集
const selectDatasetById = (datasetId) => {
  const dataset = datasets.value.find((d) => d.id === datasetId)
  if (dataset) {
    currentDataset.value = dataset
  }
}

// 获取数据集列表
const fetchDatasets = async () => {
  try {
    loading.value = true
    // 使用 /dk/sessions/mydatasets 接口
    const response = await getMyDatasets({
      search: '',
      dataset_type: 0,
    })

    // 处理数据，添加is_shared属性
    datasets.value = (response.data || []).map((dataset) => ({
      ...dataset,
      is_shared: dataset.data_source_id !== '00000000-0000-0000-0000-000000000000',
    }))

    // 从路由参数中获取数据集ID
    const datasetId = route.params.id
    if (datasetId) {
      selectDatasetById(datasetId)
    } else if (datasets.value.length > 0) {
      // 如果没有指定ID，默认选择第一个
      currentDataset.value = datasets.value[0]
    }
  } catch (error) {
    console.error('获取数据集列表失败:', error)
    ElMessage.error('获取数据集列表失败')
  } finally {
    loading.value = false
  }
}

// 监听路由参数变化
watch(
  () => route.params.id,
  (newId) => {
    if (newId && datasets.value.length > 0) {
      selectDatasetById(newId)
    }
  },
)

// 选择数据集
const selectDataset = (dataset) => {
  currentDataset.value = dataset
}

// 确认删除数据集
const confirmDeleteDataset = (dataset) => {
  ElMessageBox.confirm(`确定要删除数据集"${dataset.name}"吗？删除后将无法恢复。`, '删除数据集', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      handleDeleteDataset(dataset)
    })
    .catch(() => {
      // 用户取消删除操作
    })
}

// 处理删除数据集
const handleDeleteDataset = async (dataset) => {
  try {
    const response = await deleteMyDataset(dataset.id)
    if (response.status) {
      ElMessage.success('数据集删除成功')
      // 如果当前选中的数据集被删除，重置当前数据集
      if (currentDataset.value?.id === dataset.id) {
        currentDataset.value = null
      }
      // 重新获取数据集列表
      await fetchDatasets()
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除数据集失败:', error)
    ElMessage.error(`删除数据集失败: ${error.message || '请重试'}`)
  }
}

// 组件挂载时获取数据集列表
onMounted(() => {
  fetchDatasets()
})
</script>

<style scoped>
.dataset-component {
  height: 100vh;
  width: 100%;
  display: flex;
  color: var(--el-text-color-primary);
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

/* 左侧边栏样式 */
.dataset-sidebar {
  width: 240px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  box-shadow: var(--app-shadow-hover);
  height: 100%;
  overflow: hidden;
}

.sidebar-header {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  box-shadow: var(--app-shadow-hover);
}

.sidebar-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--app-text-primary);
}

.sidebar-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.dataset-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.dataset-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-radius: 6px;
  background-color: var(--el-fill-color-light);
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid transparent;
}

.dataset-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-color: var(--el-border-color);
}

.dataset-item.active {
  background-color: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary-light-5);
}

.dataset-icon {
  font-size: 20px;
  color: var(--el-color-primary);
  margin-right: 12px;
}

.dataset-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.dataset-title {
  font-weight: 500;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--el-text-color-primary);
  display: flex;
  align-items: center;
  gap: 6px;
}

.dataset-type {
  display: inline-block;
  padding: 1px 4px;
  background-color: #ecf5ff;
  color: #409eff;
  border-radius: 4px;
  font-size: 12px;
  width: fit-content;
  flex-shrink: 0;
}

.dataset-type.shared {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  text-align: center;
}

.empty-icon {
  font-size: 60px;
  color: var(--el-text-color-secondary);
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  color: var(--el-text-color-secondary);
  margin-bottom: 20px;
}

/* 加载状态 */
.loading-state {
  padding: 16px;
}

/* 右侧详情区域 */
.dataset-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

.empty-detail {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 深色模式样式 - 使用Element Plus变量自动适配 */
.dark-mode {
  --el-border-color: rgba(255, 255, 255, 0.1);
}

.dark-mode .dataset-item {
  background-color: #2a2a2a;
  border-color: transparent;
}

.dark-mode .dataset-item:hover {
  background-color: #333;
  border-color: #444;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.dark-mode .dataset-item.active {
  background-color: rgba(64, 158, 255, 0.2);
  border-color: rgba(64, 158, 255, 0.3);
}

.dark-mode .dataset-title {
  color: #e0e0e0;
}

.dark-mode .dataset-type {
  background-color: rgba(64, 158, 255, 0.15);
}

.dark-mode .dataset-type.shared {
  background-color: rgba(103, 194, 58, 0.15);
}

/* 数据集项操作按钮 */
.dataset-actions {
  display: flex;
  gap: 6px;
  opacity: 0;
  transition: var(--app-transition-normal, all 0.3s ease);
  align-items: center;
  margin-left: 8px;
}

.dataset-item:hover .dataset-actions {
  opacity: 1;
}

/* 删除图标样式 */
.delete-icon {
  cursor: pointer;
  color: var(--app-text-secondary, #909399);
  font-size: 16px;
  padding: 6px;
  border-radius: 50%;
  transition: all 0.3s ease;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon:hover {
  color: var(--el-color-danger);
  transform: scale(1.1);
  background-color: rgba(var(--el-color-danger-rgb), 0.1);
}

/* 深色模式适配 */
.dark-mode .delete-icon:hover {
  background-color: rgba(var(--el-color-danger-rgb), 0.2);
}
</style>
